<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>国风塔防 - 长城之战</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#8B4513',      // 木色
                        secondary: '#CD5C5C',    // 朱红色
                        accent: '#DAA520',       // 金色
                        background: '#F5F5DC',   // 宣纸色
                        dark: '#2C3E50',         // 墨色
                        tower: {
                            crossbow: '#3B82F6',  // 连弩塔-蓝色
                            fire: '#EF4444',      // 烽火台-红色
                            bagua: '#F59E0B',     // 八卦阵-黄色
                            light: '#8B5CF6'      // 佛光塔-紫色
                        }
                    },
                    fontFamily: {
                        chinese: ['"Ma Shan Zheng"', '"Noto Serif SC"', 'serif']
                    },
                    animation: {
                        'pulse-slow': 'pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite',
                        'float': 'float 3s ease-in-out infinite',
                        'shine': 'shine 2s ease-in-out infinite',
                        'burn': 'burn 1s infinite',
                        'spin-slow': 'spin 8s linear infinite'
                    },
                    keyframes: {
                        float: {
                            '0%, 100%': { transform: 'translateY(0)' },
                            '50%': { transform: 'translateY(-5px)' }
                        },
                        shine: {
                            '0%, 100%': { opacity: 0.7 },
                            '50%': { opacity: 1 }
                        },
                        burn: {
                            '0%, 100%': { transform: 'scale(1)', opacity: 0.8 },
                            '50%': { transform: 'scale(1.1)', opacity: 1 }
                        }
                    }
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .text-shadow {
                text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
            }
            .bg-pattern {
                background-image: url("data:image/svg+xml,%3Csvg width='100' height='100' viewBox='0 0 100 100' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M11 18c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm48 25c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm-43-7c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm63 31c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM34 90c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm56-76c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM12 86c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm28-65c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm23-11c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-6 60c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm29 22c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zM32 63c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm57-13c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-9-21c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM60 91c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM35 41c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM12 60c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2z' fill='%238b4513' fill-opacity='0.05' fill-rule='evenodd'/%3E%3C/svg%3E");
            }
            .tower-place {
                @apply absolute border-2 border-dashed transition-colors duration-200 cursor-pointer;
            }
            .tower-place-available {
                @apply border-primary/50 hover:border-primary/100 hover:bg-primary/10;
            }
            .tower-place-unavailable {
                @apply border-dark/30 bg-dark/30 cursor-not-allowed;
            }
            .tower-preview {
                @apply absolute opacity-70 transition-all duration-200 pointer-events-none;
            }
            .game-button {
                @apply transform transition-all duration-300 hover:scale-105 active:scale-95 focus:outline-none focus:ring-2 focus:ring-offset-2;
            }
            .game-button-primary {
                @apply game-button bg-secondary hover:bg-secondary/90 text-white focus:ring-secondary/50;
            }
            .game-button-secondary {
                @apply game-button bg-accent hover:bg-accent/90 text-white focus:ring-accent/50;
            }
            .game-button-tertiary {
                @apply game-button bg-primary hover:bg-primary/90 text-white focus:ring-primary/50;
            }
            .notification {
                @apply fixed top-20 right-4 bg-dark text-white px-4 py-2 rounded-md shadow-lg transform translate-x-full transition-transform duration-500 z-50 flex items-center gap-2;
            }
            .notification.show {
                @apply translate-x-0;
            }
            .tooltip {
                @apply invisible absolute bg-dark text-white text-xs rounded py-1 px-2 z-50 opacity-0 transition-opacity duration-200 pointer-events-none whitespace-nowrap;
            }
            .has-tooltip:hover .tooltip {
                @apply visible opacity-100;
            }
        }
    </style>
    <link href="https://fonts.googleapis.com/css2?family=Ma+Shan+Zheng&family=Noto+Serif+SC:wght@400;700&display=swap" rel="stylesheet">
</head>
<body class="bg-background bg-pattern min-h-screen text-dark overflow-x-hidden">
    <!-- 顶部导航 -->
    <header class="bg-primary/95 text-background shadow-lg backdrop-blur-sm">
        <div class="container mx-auto px-4 py-3 flex flex-wrap justify-between items-center">
            <div class="flex items-center space-x-3 mb-2 sm:mb-0">
                <div class="relative">
                    <i class="fa fa-shield text-accent text-2xl animate-spin-slow"></i>
                    <div class="absolute -top-1 -right-1 w-3 h-3 bg-secondary rounded-full border-2 border-background"></div>
                </div>
                <h1 class="font-chinese text-xl md:text-2xl text-shadow">国风塔防 - 长城之战</h1>
            </div>
            <div class="flex items-center space-x-6">
                <div class="flex items-center has-tooltip">
                    <i class="fa fa-coins text-accent mr-2 text-lg"></i>
                    <span id="money" class="font-chinese text-lg">500</span>
                    <span class="tooltip bottom-full right-0 mb-1">可用铜钱</span>
                </div>
                <div class="flex items-center has-tooltip">
                    <i class="fa fa-heart text-secondary mr-2 text-lg animate-pulse"></i>
                    <span id="lives" class="font-chinese text-lg">10</span>
                    <span class="tooltip bottom-full right-0 mb-1">剩余生命值</span>
                </div>
                <div class="flex items-center has-tooltip">
                    <i class="fa fa-clock-o text-background mr-2 text-lg"></i>
                    <span id="wave" class="font-chinese text-lg">第1波</span>
                    <span class="tooltip bottom-full right-0 mb-1">当前波次</span>
                </div>
            </div>
        </div>
    </header>

    <!-- 游戏主区域 -->
    <main class="container mx-auto px-4 py-6 flex flex-col lg:flex-row gap-6">
        <!-- 游戏地图区域 - 使用Canvas -->
        <div class="lg:w-3/4 relative bg-[#E8D9B5]/80 rounded-lg shadow-xl border-4 border-primary/30 overflow-hidden transition-all duration-500 hover:shadow-2xl">
            <div class="absolute top-4 left-4 z-10 bg-dark/70 text-background px-3 py-1 rounded-full text-sm backdrop-blur-sm">
                <i class="fa fa-map-o mr-1"></i> 长城防线
            </div>
            
            <div class="w-full aspect-[4/3] relative">
                <!-- 装饰性卷轴边框 -->
                <div class="absolute -left-2 top-0 bottom-0 w-8 bg-[url('')] bg-repeat-y opacity-70 pointer-events-none"></div>
                <div class="absolute -right-2 top-0 bottom-0 w-8 bg-[url('')] bg-repeat-y opacity-70 pointer-events-none"></div>
                
                <!-- 游戏Canvas -->
                <canvas id="gameCanvas" class="w-full h-full absolute top-0 left-0"></canvas>
                
                <!-- 防御塔可放置位置（透明定位点，用于交互） -->
                <div class="tower-place tower-place-available absolute w-12 h-12 top-[15%] left-[30%]" data-x="30" data-y="15"></div>
                <div class="tower-place tower-place-available absolute w-12 h-12 top-[15%] left-[60%]" data-x="60" data-y="15"></div>
                <div class="tower-place tower-place-available absolute w-12 h-12 top-[40%] left-[10%]" data-x="10" data-y="40"></div>
                <div class="tower-place tower-place-available absolute w-12 h-12 top-[40%] left-[40%]" data-x="40" data-y="40"></div>
                <div class="tower-place tower-place-available absolute w-12 h-12 top-[40%] left-[70%]" data-x="70" data-y="40"></div>
                <div class="tower-place tower-place-available absolute w-12 h-12 top-[65%] left-[30%]" data-x="30" data-y="65"></div>
                <div class="tower-place tower-place-available absolute w-12 h-12 top-[65%] left-[60%]" data-x="60" data-y="65"></div>
                
                <!-- 游戏状态覆盖层 -->
                <div id="game-overlay" class="absolute inset-0 bg-dark/70 flex items-center justify-center backdrop-blur-sm">
                    <div class="bg-background p-8 rounded-lg shadow-2xl border-2 border-accent/30 max-w-md w-full mx-4 transform transition-all duration-500 hover:scale-105">
                        <div class="text-center mb-6">
                            <div class="inline-block p-3 rounded-full bg-primary/10 mb-4">
                                <i class="fa fa-flag text-4xl text-primary animate-pulse-slow"></i>
                            </div>
                            <h2 class="font-chinese text-3xl text-primary mb-2 text-shadow" id="overlay-title">准备战斗</h2>
                            <p class="text-dark/80" id="overlay-message">点击开始按钮，抵御第一波敌人的进攻，守护长城防线</p>
                        </div>
                        <button id="start-button" class="game-button-primary font-chinese py-3 px-8 rounded-md text-lg w-full">
                            开始战斗
                        </button>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 游戏控制面板 -->
        <div class="lg:w-1/4 flex flex-col gap-6">
            <!-- 玩家信息卡片 -->
            <div class="bg-white rounded-lg shadow-md p-4 border border-primary/20 transform transition-all duration-300 hover:shadow-lg">
                <div class="flex items-center gap-3 mb-3">
                    <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center">
                        <i class="fa fa-user text-primary"></i>
                    </div>
                    <div>
                        <h3 class="font-chinese text-primary">守将</h3>
                        <p class="text-xs text-dark/60">长城守卫者</p>
                    </div>
                </div>
                <div class="grid grid-cols-2 gap-2 text-sm">
                    <div class="bg-gray-50 p-2 rounded">
                        <div class="text-xs text-dark/60">已击败敌人</div>
                        <div id="enemies-killed" class="font-chinese text-primary">0</div>
                    </div>
                    <div class="bg-gray-50 p-2 rounded">
                        <div class="text-xs text-dark/60">最高波次</div>
                        <div id="highest-wave" class="font-chinese text-primary">0</div>
                    </div>
                </div>
            </div>
            
            <!-- 防御塔选择面板 -->
            <div class="bg-white rounded-lg shadow-md p-4 border border-primary/20 transform transition-all duration-300 hover:shadow-lg">
                <h2 class="font-chinese text-xl text-primary mb-3 border-b border-primary/20 pb-2 flex items-center">
                    <i class="fa fa-fort-awesome mr-2"></i>防御塔选择
                </h2>
                <div class="grid grid-cols-2 gap-3">
                    <!-- 连弩塔 -->
                    <div class="tower-select group bg-blue-50 border-2 border-tower-crossbow/50 hover:border-tower-crossbow rounded-md p-3 cursor-pointer transition-all duration-300 transform hover:-translate-y-1" data-tower="crossbow" data-cost="100">
                        <div class="flex justify-center mb-2">
                            <i class="fa fa-crosshairs text-tower-crossbow text-xl group-hover:animate-pulse"></i>
                        </div>
                        <div class="text-center text-sm">
                            <div class="font-chinese">连弩塔</div>
                            <div class="text-xs text-dark/70 mt-1"><i class="fa fa-bolt text-yellow-500 mr-1"></i> 快速攻击</div>
                            <div class="mt-1"><i class="fa fa-coins text-accent text-xs"></i> 100</div>
                        </div>
                    </div>
                    
                    <!-- 烽火台 -->
                    <div class="tower-select group bg-red-50 border-2 border-tower-fire/50 hover:border-tower-fire rounded-md p-3 cursor-pointer transition-all duration-300 transform hover:-translate-y-1" data-tower="fire" data-cost="150">
                        <div class="flex justify-center mb-2">
                            <i class="fa fa-fire text-tower-fire text-xl group-hover:animate-burn"></i>
                        </div>
                        <div class="text-center text-sm">
                            <div class="font-chinese">烽火台</div>
                            <div class="text-xs text-dark/70 mt-1"><i class="fa fa-area-chart text-red-500 mr-1"></i> 范围伤害</div>
                            <div class="mt-1"><i class="fa fa-coins text-accent text-xs"></i> 150</div>
                        </div>
                    </div>
                    
                    <!-- 八卦阵 -->
                    <div class="tower-select group bg-yellow-50 border-2 border-tower-bagua/50 hover:border-tower-bagua rounded-md p-3 cursor-pointer transition-all duration-300 transform hover:-translate-y-1" data-tower="八卦" data-cost="200">
                        <div class="flex justify-center mb-2">
                            <i class="fa fa-th text-tower-bagua text-xl group-hover:animate-spin-slow"></i>
                        </div>
                        <div class="text-center text-sm">
                            <div class="font-chinese">八卦阵</div>
                            <div class="text-xs text-dark/70 mt-1"><i class="fa fa-clock-o text-yellow-600 mr-1"></i> 减速敌人</div>
                            <div class="mt-1"><i class="fa fa-coins text-accent text-xs"></i> 200</div>
                        </div>
                    </div>
                    
                    <!-- 佛光塔 -->
                    <div class="tower-select group bg-purple-50 border-2 border-tower-light/50 hover:border-tower-light rounded-md p-3 cursor-pointer transition-all duration-300 transform hover:-translate-y-1" data-tower="light" data-cost="250">
                        <div class="flex justify-center mb-2">
                            <i class="fa fa-star text-tower-light text-xl group-hover:animate-shine"></i>
                        </div>
                        <div class="text-center text-sm">
                            <div class="font-chinese">佛光塔</div>
                            <div class="text-xs text-dark/70 mt-1"><i class="fa fa-magic text-purple-500 mr-1"></i> 穿透伤害</div>
                            <div class="mt-1"><i class="fa fa-coins text-accent text-xs"></i> 250</div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 敌人图鉴 -->
            <div class="bg-white rounded-lg shadow-md p-4 border border-primary/20 transform transition-all duration-300 hover:shadow-lg">
                <h2 class="font-chinese text-xl text-primary mb-3 border-b border-primary/20 pb-2 flex items-center">
                    <i class="fa fa-book mr-2"></i>异兽图鉴
                </h2>
                <div class="space-y-3 max-h-48 overflow-y-auto pr-1 scrollbar-thin scrollbar-thumb-primary/30">
                    <div class="flex items-center gap-3 p-2 bg-gray-50 rounded-lg transform transition-all duration-200 hover:bg-gray-100">
                        <div class="w-8 h-8 bg-amber-700 rounded-full flex items-center justify-center text-white">
                            <i class="fa fa-horse"></i>
                        </div>
                        <div>
                            <div class="text-sm font-chinese">匈奴骑兵</div>
                            <div class="text-xs text-dark/70">速度快，血量中等</div>
                        </div>
                    </div>
                    <div class="flex items-center gap-3 p-2 bg-gray-50 rounded-lg transform transition-all duration-200 hover:bg-gray-100">
                        <div class="w-8 h-8 bg-emerald-700 rounded-full flex items-center justify-center text-white">
                            <i class="fa fa-shield"></i>
                        </div>
                        <div>
                            <div class="text-sm font-chinese">饕餮</div>
                            <div class="text-xs text-dark/70">血量高，移动慢</div>
                        </div>
                    </div>
                    <div class="flex items-center gap-3 p-2 bg-gray-50 rounded-lg transform transition-all duration-200 hover:bg-gray-100">
                        <div class="w-8 h-8 bg-red-600 rounded-full flex items-center justify-center text-white">
                            <i class="fa fa-fire"></i>
                        </div>
                        <div>
                            <div class="text-sm font-chinese">毕方</div>
                            <div class="text-xs text-dark/70">对火属性免疫</div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 操作按钮 -->
            <div class="flex gap-3">
                <button id="next-wave" class="game-button-secondary flex-1 font-chinese py-3 px-4 rounded-md disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none disabled:hover:scale-100" disabled>
                    <i class="fa fa-forward mr-1"></i> 下一波
                </button>
                <button id="restart" class="game-button-tertiary flex-1 font-chinese py-3 px-4 rounded-md">
                    <i class="fa fa-refresh mr-1"></i> 重新开始
                </button>
            </div>
            
            <!-- 游戏提示 -->
            <div class="bg-primary/10 rounded-lg p-3 text-sm border border-primary/20">
                <h3 class="font-chinese text-primary mb-2 flex items-center">
                    <i class="fa fa-lightbulb-o mr-1"></i> 战术提示
                </h3>
                <ul class="list-disc pl-5 space-y-1 text-dark/80">
                    <li>连弩塔适合对付快速移动的敌人</li>
                    <li>八卦阵可以减缓敌人速度，配合其他塔效果更佳</li>
                    <li>毕方对火焰伤害免疫，避免使用烽火台攻击</li>
                    <li>每3波会获得额外铜钱奖励</li>
                </ul>
            </div>
        </div>
    </main>

    <!-- 塔防信息面板 -->
    <div id="tower-info" class="fixed bottom-6 left-1/2 transform -translate-x-1/2 bg-white rounded-lg shadow-xl p-4 border-2 border-primary/30 w-72 z-50 transition-all duration-300 scale-95 opacity-0 pointer-events-none" style="display: none;">
        <div class="flex justify-between items-start mb-3">
            <h3 class="font-chinese text-primary text-lg" id="tower-info-name">连弩塔</h3>
            <button id="close-tower-info" class="text-dark/50 hover:text-dark transition-colors">
                <i class="fa fa-times"></i>
            </button>
        </div>
        <div class="space-y-2 text-sm mb-4">
            <div class="flex justify-between p-2 bg-gray-50 rounded">
                <span class="flex items-center"><i class="fa fa-bolt text-yellow-500 mr-1"></i> 攻击力</span>
                <span id="tower-info-attack" class="font-semibold">10</span>
            </div>
            <div class="flex justify-between p-2 bg-gray-50 rounded">
                <span class="flex items-center"><i class="fa fa-arrows-h text-blue-500 mr-1"></i> 攻击范围</span>
                <span id="tower-info-range" class="font-semibold">15%</span>
            </div>
            <div class="flex justify-between p-2 bg-gray-50 rounded">
                <span class="flex items-center"><i class="fa fa-clock-o text-green-500 mr-1"></i> 攻击速度</span>
                <span id="tower-info-speed" class="font-semibold">快</span>
            </div>
            <div class="flex justify-between p-2 bg-gray-50 rounded" id="tower-special-effect" style="display: none;">
                <span class="flex items-center"><i class="fa fa-magic text-purple-500 mr-1"></i> 特殊效果</span>
                <span id="tower-effect-text" class="font-semibold"></span>
            </div>
        </div>
        <div class="flex gap-2">
            <button id="upgrade-tower" class="game-button-secondary flex-1 text-sm py-2 rounded">
                <i class="fa fa-level-up mr-1"></i> 升级 (100)
            </button>
            <button id="sell-tower" class="game-button-tertiary flex-1 text-sm py-2 rounded">
                <i class="fa fa-money mr-1"></i> 出售
            </button>
        </div>
    </div>

    <!-- 通知提示框 -->
    <div id="notification" class="notification">
        <i class="fa fa-info-circle"></i>
        <span id="notification-text">通知内容</span>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 游戏统计数据
            const gameStats = {
                enemiesKilled: 0,
                highestWave: 0
            };
            
            // 获取DOM元素
            const enemiesKilledEl = document.getElementById('enemies-killed');
            const highestWaveEl = document.getElementById('highest-wave');
            const notificationEl = document.getElementById('notification');
            const notificationTextEl = document.getElementById('notification-text');
            
            // 显示通知
            function showNotification(message, type = 'info') {
                // 设置图标和颜色
                let icon = 'fa-info-circle';
                if (type === 'success') icon = 'fa-check-circle text-green-400';
                else if (type === 'warning') icon = 'fa-exclamation-triangle text-yellow-400';
                else if (type === 'error') icon = 'fa-times-circle text-red-400';
                
                // 更新内容
                notificationEl.innerHTML = `<i class="fa ${icon}"></i><span id="notification-text">${message}</span>`;
                
                // 显示通知
                notificationEl.classList.add('show');
                
                // 3秒后隐藏
                setTimeout(() => {
                    notificationEl.classList.remove('show');
                }, 3000);
            }
            
            // 更新统计数据
            function updateStats() {
                enemiesKilledEl.textContent = gameStats.enemiesKilled;
                highestWaveEl.textContent = Math.max(gameStats.highestWave, gameState.wave);
            }
            
            // 获取Canvas元素并设置上下文
            const canvas = document.getElementById('gameCanvas');
            const ctx = canvas.getContext('2d');
            
            // 设置Canvas尺寸以匹配显示尺寸
            function resizeCanvas() {
                const container = canvas.parentElement;
                canvas.width = container.clientWidth;
                canvas.height = container.clientHeight;
                // 重绘所有元素
                drawGame();
            }
            
            // 初始化时调整尺寸，并监听窗口大小变化
            resizeCanvas();
            window.addEventListener('resize', resizeCanvas);
            
            // 加载背景图片和装饰元素
            const backgroundImg = new Image();
            backgroundImg.src = 'https://picsum.photos/id/1039/1200/900';
            
            const cloudImg = new Image();
            cloudImg.src = 'https://picsum.photos/id/235/200/100';
            
            const decorativeElements = [
                {type: 'cloud', x: 10, y: 5, size: 0.8, speed: 0.02},
                {type: 'cloud', x: 70, y: 10, size: 1, speed: 0.015},
                {type: 'cloud', x: 40, y: 8, size: 0.7, speed: 0.025},
                {type: 'bird', x: 20, y: 15, size: 0.3, speed: 0.1},
                {type: 'bird', x: 80, y: 20, size: 0.25, speed: 0.12}
            ];
            
            // 游戏状态变量
            const gameState = {
                money: 500,
                lives: 10,
                wave: 1,
                isPlaying: false,
                selectedTower: null,
                towers: [],
                enemies: [],
                currentEnemyId: 0,
                gameLoop: null,
                attackEffects: [],
                pathPoints: [
                    {x: 0, y: 25},   // 起点
                    {x: 25, y: 25},
                    {x: 50, y: 25},
                    {x: 50, y: 40},
                    {x: 50, y: 60},
                    {x: 25, y: 60},
                    {x: 0, y: 60},
                    {x: 50, y: 60},
                    {x: 75, y: 60},
                    {x: 100, y: 60}  // 终点
                ],
                // 粒子效果
                particles: []
            };
            
            // DOM元素
            const moneyEl = document.getElementById('money');
            const livesEl = document.getElementById('lives');
            const waveEl = document.getElementById('wave');
            const gameOverlay = document.getElementById('game-overlay');
            const overlayTitle = document.getElementById('overlay-title');
            const overlayMessage = document.getElementById('overlay-message');
            const startButton = document.getElementById('start-button');
            const nextWaveButton = document.getElementById('next-wave');
            const restartButton = document.getElementById('restart');
            const towerSelects = document.querySelectorAll('.tower-select');
            const towerPlaces = document.querySelectorAll('.tower-place-available');
            const towerInfo = document.getElementById('tower-info');
            const towerInfoName = document.getElementById('tower-info-name');
            const towerInfoAttack = document.getElementById('tower-info-attack');
            const towerInfoRange = document.getElementById('tower-info-range');
            const towerInfoSpeed = document.getElementById('tower-info-speed');
            const towerSpecialEffect = document.getElementById('tower-special-effect');
            const towerEffectText = document.getElementById('tower-effect-text');
            const closeTowerInfo = document.getElementById('close-tower-info');
            const upgradeTower = document.getElementById('upgrade-tower');
            const sellTower = document.getElementById('sell-tower');
            
            // 创建塔预览元素
            const towerPreview = document.createElement('div');
            towerPreview.className = 'tower-preview';
            towerPreview.style.display = 'none';
            document.body.appendChild(towerPreview);
            
            // 塔的类型定义 - 增强细节描述
            const towerTypes = {
                crossbow: {
                    name: '连弩塔',
                    color: '#3B82F6', // 蓝色
                    attack: 10,
                    range: 15,
                    speed: 500,
                    cost: 100,
                    upgradeCost: 100,
                    specialEffect: null,
                    // 连弩塔细节：多层结构，带箭簇装饰
                    draw: function(ctx, x, y, size, level) {
                        // 塔底座
                        ctx.fillStyle = '#1E40AF';
                        ctx.fillRect(x - size/4, y - size/4, size/2, size/2);
                        
                        // 底座纹理
                        ctx.fillStyle = '#3B82F6';
                        for(let i = 0; i < 3; i++) {
                            for(let j = 0; j < 3; j++) {
                                const brickSize = size/12;
                                ctx.fillRect(
                                    x - size/4 + i*brickSize + (j%2 === 0 ? 0 : brickSize/2),
                                    y - size/4 + j*brickSize,
                                    brickSize*0.8,
                                    brickSize*0.8
                                );
                            }
                        }
                        
                        // 塔主体
                        ctx.fillStyle = this.color;
                        ctx.fillRect(x - size/6, y - size*0.4, size/3, size*0.6);
                        
                        // 连弩装置
                        ctx.fillStyle = '#93C5FD';
                        const arrowLength = size * 0.3 + (level - 1) * size * 0.05;
                        // 四个方向的弩箭
                        for(let i = 0; i < 4; i++) {
                            const angle = i * Math.PI/2;
                            ctx.save();
                            ctx.translate(x, y);
                            ctx.rotate(angle);
                            ctx.fillRect(-size/12, -size/12, arrowLength, size/6);
                            // 箭头
                            ctx.beginPath();
                            ctx.moveTo(arrowLength, 0);
                            ctx.lineTo(arrowLength - size/8, -size/8);
                            ctx.lineTo(arrowLength - size/8, size/8);
                            ctx.closePath();
                            ctx.fillStyle = '#DBEAFE';
                            ctx.fill();
                            ctx.restore();
                        }
                        
                        // 等级装饰
                        if(level > 1) {
                            ctx.fillStyle = '#DAA520';
                            ctx.beginPath();
                            ctx.arc(x, y + size/2, size/8, 0, Math.PI * 2);
                            ctx.fill();
                            ctx.fillStyle = '#FFFFFF';
                            ctx.font = `${size/4}px Arial`;
                            ctx.textAlign = 'center';
                            ctx.textBaseline = 'middle';
                            ctx.fillText(`${level}`, x, y + size/2);
                        }
                        
                        // 升级特效
                        if(level > 1) {
                            ctx.strokeStyle = `rgba(218, 165, 32, ${0.3 + Math.sin(Date.now()/300) * 0.1})`;
                            ctx.lineWidth = 2;
                            ctx.beginPath();
                            ctx.arc(x, y, size/3 + (level-1)*size/10, 0, Math.PI * 2);
                            ctx.stroke();
                        }
                    }
                },
                fire: {
                    name: '烽火台',
                    color: '#EF4444', // 红色
                    attack: 20,
                    range: 10,
                    speed: 1500,
                    cost: 150,
                    upgradeCost: 150,
                    specialEffect: "范围伤害",
                    // 烽火台细节：带火焰效果，砖石结构
                    draw: function(ctx, x, y, size, level) {
                        // 砖石底座
                        ctx.fillStyle = '#9CA3AF';
                        ctx.fillRect(x - size/3, y - size/4, size*2/3, size/2);
                        
                        // 绘制砖块纹理
                        ctx.strokeStyle = '#6B7280';
                        ctx.lineWidth = 1;
                        const brickSize = size/10;
                        for(let i = 0; i < 3; i++) {
                            for(let j = 0; j < 4; j++) {
                                const offsetX = i % 2 === 0 ? 0 : brickSize/2;
                                ctx.strokeRect(
                                    x - size/3 + j*brickSize + offsetX,
                                    y - size/4 + i*brickSize,
                                    brickSize,
                                    brickSize
                                );
                            }
                        }
                        
                        // 烽火台主体
                        ctx.fillStyle = this.color;
                        ctx.beginPath();
                        ctx.ellipse(x, y - size/6, size/4, size/3, 0, 0, Math.PI * 2);
                        ctx.fill();
                        
                        // 火焰效果（动态变化）
                        const time = Date.now() / 300;
                        const flameHeight = size/3 + Math.sin(time) * size/10;
                        
                        ctx.fillStyle = '#FBBF24';
                        ctx.beginPath();
                        ctx.moveTo(x, y - size/3);
                        ctx.bezierCurveTo(
                            x - size/6 + Math.sin(time + 1) * size/20, y - size/3 - flameHeight,
                            x + size/6 + Math.sin(time) * size/20, y - size/3 - flameHeight,
                            x, y - size/3
                        );
                        ctx.closePath();
                        ctx.fill();
                        
                        // 火焰外层
                        ctx.fillStyle = '#FB923C';
                        ctx.beginPath();
                        ctx.moveTo(x, y - size/3 + size/10);
                        ctx.bezierCurveTo(
                            x - size/5 + Math.sin(time + 2) * size/15, y - size/3 - flameHeight * 0.8,
                            x + size/5 + Math.sin(time + 3) * size/15, y - size/3 - flameHeight * 0.8,
                            x, y - size/3 + size/10
                        );
                        ctx.closePath();
                        ctx.fill();
                        
                        // 等级标记
                        if(level > 1) {
                            ctx.fillStyle = '#DAA520';
                            ctx.beginPath();
                            ctx.arc(x, y + size/2, size/8, 0, Math.PI * 2);
                            ctx.fill();
                            ctx.fillStyle = '#FFFFFF';
                            ctx.font = `${size/4}px Arial`;
                            ctx.textAlign = 'center';
                            ctx.textBaseline = 'middle';
                            ctx.fillText(`${level}`, x, y + size/2);
                        }
                    }
                },
                '八卦': {
                    name: '八卦阵',
                    color: '#F59E0B', // 黄色
                    attack: 5,
                    range: 20,
                    speed: 1000,
                    cost: 200,
                    upgradeCost: 200,
                    slow: 0.5,
                    specialEffect: "减速50%",
                    // 八卦阵细节：绘制八卦图案
                    draw: function(ctx, x, y, size, level) {
                        // 八卦底座
                        ctx.fillStyle = '#D97706';
                        ctx.beginPath();
                        ctx.ellipse(x, y, size/3, size/3, 0, 0, Math.PI * 2);
                        ctx.fill();
                        
                        // 旋转动画效果
                        const rotation = (Date.now() / 3000) % (Math.PI * 2);
                        ctx.save();
                        ctx.translate(x, y);
                        ctx.rotate(rotation);
                        
                        // 绘制八卦图案
                        ctx.lineWidth = 2;
                        ctx.strokeStyle = '#FFFFFF';
                        ctx.beginPath();
                        ctx.ellipse(0, 0, size/4, size/4, 0, 0, Math.PI * 2);
                        ctx.stroke();
                        
                        // 阴阳线
                        ctx.beginPath();
                        ctx.moveTo(0, -size/4);
                        ctx.lineTo(0, size/4);
                        ctx.stroke();
                        
                        // 阴阳鱼
                        ctx.fillStyle = '#FFFFFF';
                        ctx.beginPath();
                        ctx.ellipse(0, -size/8, size/8, size/8, 0, 0, Math.PI * 2);
                        ctx.fill();
                        
                        ctx.fillStyle = '#D97706';
                        ctx.beginPath();
                        ctx.ellipse(0, size/8, size/8, size/8, 0, 0, Math.PI * 2);
                        ctx.fill();
                        
                        // 小圆点
                        ctx.fillStyle = '#D97706';
                        ctx.beginPath();
                        ctx.ellipse(0, -size/8, size/32, size/32, 0, 0, Math.PI * 2);
                        ctx.fill();
                        
                        ctx.fillStyle = '#FFFFFF';
                        ctx.beginPath();
                        ctx.ellipse(0, size/8, size/32, size/32, 0, 0, Math.PI * 2);
                        ctx.fill();
                        
                        // 八卦符号
                        const symbols = [
                            {angle: 0, lines: 3},    // 乾
                            {angle: Math.PI/4, lines: 2}, // 兑
                            {angle: Math.PI/2, lines: 1}, // 离
                            {angle: 3*Math.PI/4, lines: 6}, // 震
                            {angle: Math.PI, lines: 5}, // 巽
                            {angle: 5*Math.PI/4, lines: 4}, // 坎
                            {angle: 3*Math.PI/2, lines: 7}, // 艮
                            {angle: 7*Math.PI/4, lines: 8}  // 坤
                        ];
                        
                        symbols.forEach(sym => {
                            const radius = size/4 * 0.8;
                            const sx = Math.cos(sym.angle) * radius;
                            const sy = Math.sin(sym.angle) * radius;
                            drawTrigram(ctx, sx, sy, size/12, sym.angle);
                        });
                        
                        ctx.restore();
                        
                        // 等级标记
                        if(level > 1) {
                            ctx.fillStyle = '#DAA520';
                            ctx.beginPath();
                            ctx.arc(x, y + size/2, size/8, 0, Math.PI * 2);
                            ctx.fill();
                            ctx.fillStyle = '#FFFFFF';
                            ctx.font = `${size/4}px Arial`;
                            ctx.textAlign = 'center';
                            ctx.textBaseline = 'middle';
                            ctx.fillText(`${level}`, x, y + size/2);
                        }
                        
                        // 八卦阵光环效果
                        ctx.strokeStyle = `rgba(245, 158, 11, ${0.3 + Math.sin(Date.now()/500) * 0.1})`;
                        ctx.lineWidth = 2;
                        ctx.beginPath();
                        ctx.arc(x, y, size/3 + 2, 0, Math.PI * 2);
                        ctx.stroke();
                    }
                },
                light: {
                    name: '佛光塔',
                    color: '#8B5CF6', // 紫色
                    attack: 15,
                    range: 15,
                    speed: 1000,
                    cost: 250,
                    upgradeCost: 250,
                    specialEffect: "穿透伤害",
                    // 佛光塔细节：带光环效果，莲花底座
                    draw: function(ctx, x, y, size, level) {
                        // 莲花底座
                        drawLotus(ctx, x, y, size/3, 8, level);
                        
                        // 塔主体
                        ctx.fillStyle = this.color;
                        ctx.beginPath();
                        ctx.moveTo(x, y - size/2);
                        ctx.lineTo(x - size/6, y - size/6);
                        ctx.lineTo(x + size/6, y - size/6);
                        ctx.closePath();
                        ctx.fill();
                        
                        // 塔身纹理
                        ctx.fillStyle = '#A78BFA';
                        for(let i = 0; i < 3; i++) {
                            const height = (y - size/6) - (y - size/2) = size/3;
                            const segmentHeight = height / 4;
                            ctx.beginPath();
                            ctx.moveTo(x - size/8 + i*size/40, y - size/2 + segmentHeight*(i+1));
                            ctx.lineTo(x + size/8 - i*size/40, y - size/2 + segmentHeight*(i+1));
                            ctx.strokeStyle = '#C4B5FD';
                            ctx.lineWidth = 1;
                            ctx.stroke();
                        }
                        
                        // 塔顶
                        ctx.fillStyle = '#C084FC';
                        ctx.beginPath();
                        ctx.moveTo(x, y - size/2);
                        ctx.lineTo(x - size/8, y - size/3);
                        ctx.lineTo(x + size/8, y - size/3);
                        ctx.closePath();
                        ctx.fill();
                        
                        // 佛光效果（动态变化）
                        const time = Date.now() / 1000;
                        const glowSize = size/4 + Math.sin(time) * size/20;
                        
                        ctx.strokeStyle = `rgba(233, 213, 255, ${0.6 + Math.sin(time * 2) * 0.2})`;
                        ctx.lineWidth = 3;
                        ctx.beginPath();
                        ctx.ellipse(x, y - size/4, glowSize, glowSize * 0.6, 0, 0, Math.PI * 2);
                        ctx.stroke();
                        
                        ctx.strokeStyle = `rgba(216, 180, 254, ${0.4 + Math.sin(time * 2 + 1) * 0.2})`;
                        ctx.lineWidth = 2;
                        ctx.beginPath();
                        ctx.ellipse(x, y - size/4, glowSize * 1.3, glowSize * 0.8, 0, 0, Math.PI * 2);
                        ctx.stroke();
                        
                        // 等级标记
                        if(level > 1) {
                            ctx.fillStyle = '#DAA520';
                            ctx.beginPath();
                            ctx.arc(x, y + size/2, size/8, 0, Math.PI * 2);
                            ctx.fill();
                            ctx.fillStyle = '#FFFFFF';
                            ctx.font = `${size/4}px Arial`;
                            ctx.textAlign = 'center';
                            ctx.textBaseline = 'middle';
                            ctx.fillText(`${level}`, x, y + size/2);
                        }
                    }
                }
            };
            
            // 辅助函数：绘制八卦符号
            function drawTrigram(ctx, x, y, size, angle) {
                ctx.save();
                ctx.translate(x, y);
                ctx.rotate(angle + Math.PI/2);
                ctx.strokeStyle = '#FFFFFF';
                ctx.lineWidth = 1;
                
                // 绘制三条线
                for(let i = 0; i < 3; i++) {
                    const yPos = -size + i * size/2;
                    ctx.beginPath();
                    ctx.moveTo(-size/2, yPos);
                    ctx.lineTo(size/2, yPos);
                    ctx.stroke();
                }
                
                ctx.restore();
            }
            
            // 辅助函数：绘制莲花底座
            function drawLotus(ctx, x, y, size, petals, level) {
                const time = Date.now() / 2000;
                for(let i = 0; i < petals + (level-1)*2; i++) {
                    const angle = (i / (petals + (level-1)*2)) * Math.PI * 2 + time;
                    const petalX = x + Math.cos(angle) * size * 0.7;
                    const petalY = y + Math.sin(angle) * size * 0.7;
                    const petalSize = size/4 + Math.sin(angle * 2 + time) * size/20;
                    
                    ctx.save();
                    ctx.translate(petalX, petalY);
                    ctx.rotate(angle);
                    
                    ctx.beginPath();
                    ctx.ellipse(0, 0, petalSize, petalSize/2, 0, 0, Math.PI * 2);
                    ctx.fillStyle = `rgba(237, 233, 254, ${0.7 + Math.sin(angle * 3 + time) * 0.2})`;
                    ctx.fill();
                    
                    ctx.restore();
                }
            }
            
            // 敌人类型定义
            const enemyTypes = {
                soldier: {
                    name: '匈奴骑兵',
                    color: '#B45309', // 棕色
                    health: 50,
                    speed: 1,
                    reward: 50,
                    draw: function(ctx, x, y, size, healthPercent) {
                        // 骑兵身体
                        ctx.fillStyle = this.color;
                        ctx.beginPath();
                        ctx.ellipse(x, y, size/2, size/3, 0, 0, Math.PI * 2);
                        ctx.fill();
                        
                        // 身体纹理
                        ctx.strokeStyle = '#92400E';
                        ctx.lineWidth = 1;
                        ctx.beginPath();
                        ctx.moveTo(x - size/2, y);
                        ctx.lineTo(x + size/2, y);
                        ctx.stroke();
                        
                        // 骑兵头部
                        ctx.fillStyle = '#92400E';
                        ctx.beginPath();
                        ctx.ellipse(x, y - size/3, size/4, size/4, 0, 0, Math.PI * 2);
                        ctx.fill();
                        
                        // 眼睛
                        ctx.fillStyle = '#FFFFFF';
                        ctx.beginPath();
                        ctx.ellipse(x + size/12, y - size/3, size/20, size/20, 0, 0, Math.PI * 2);
                        ctx.fill();
                        
                        // 骑兵武器
                        ctx.fillStyle = '#4B5563';
                        ctx.beginPath();
                        ctx.rect(x + size/4, y - size/4, size/2, size/8);
                        ctx.fill();
                        
                        // 武器细节
                        ctx.fillStyle = '#6B7280';
                        ctx.beginPath();
                        ctx.rect(x + size/4 + size/3, y - size/4, size/6, size/8);
                        ctx.fill();
                        
                        // 绘制血量
                        drawHealthBar(ctx, x, y - size/2, size, healthPercent);
                        
                        // 呼吸效果
                        const scale = 1 + Math.sin(Date.now()/500) * 0.03;
                        ctx.save();
                        ctx.translate(x, y);
                        ctx.scale(scale, 1);
                        ctx.restore();
                    }
                },
                taotie: {
                    name: '饕餮',
                    color: '#059669', // 绿色
                    health: 150,
                    speed: 0.5,
                    reward: 150,
                    draw: function(ctx, x, y, size, healthPercent) {
                        // 饕餮身体
                        ctx.fillStyle = this.color;
                        ctx.beginPath();
                        ctx.ellipse(x, y, size/2, size/2, 0, 0, Math.PI * 2);
                        ctx.fill();
                        
                        // 身体纹理
                        ctx.fillStyle = '#065F46';
                        for(let i = 0; i < 5; i++) {
                            const angle = (i / 5) * Math.PI * 2;
                            const offset = size/5;
                            ctx.beginPath();
                            ctx.arc(
                                x + Math.cos(angle) * offset,
                                y + Math.sin(angle) * offset,
                                size/15, 0, Math.PI * 2
                            );
                            ctx.fill();
                        }
                        
                        // 饕餮头部
                        ctx.fillStyle = '#065F46';
                        ctx.beginPath();
                        ctx.ellipse(x, y, size/3, size/3, 0, 0, Math.PI * 2);
                        ctx.fill();
                        
                        // 饕餮眼睛
                        ctx.fillStyle = '#FFFFFF';
                        ctx.beginPath();
                        ctx.ellipse(x - size/8, y - size/10, size/12, size/12, 0, 0, Math.PI * 2);
                        ctx.ellipse(x + size/8, y - size/10, size/12, size/12, 0, 0, Math.PI * 2);
                        ctx.fill();
                        
                        // 眼球
                        ctx.fillStyle = '#000000';
                        ctx.beginPath();
                        ctx.ellipse(x - size/8 + size/40, y - size/10, size/30, size/30, 0, 0, Math.PI * 2);
                        ctx.ellipse(x + size/8 + size/40, y - size/10, size/30, size/30, 0, 0, Math.PI * 2);
                        ctx.fill();
                        
                        // 饕餮嘴巴
                        ctx.fillStyle = '#033F30';
                        ctx.beginPath();
                        ctx.arc(x, y + size/10, size/10, 0, Math.PI, false);
                        ctx.fill();
                        
                        // 牙齿
                        ctx.fillStyle = '#FFFFFF';
                        for(let i = 0; i < 5; i++) {
                            const angle = Math.PI/6 + (i * Math.PI/6);
                            const toothX = x + Math.cos(angle) * size/10;
                            const toothY = y + Math.sin(angle) * size/10;
                            ctx.beginPath();
                            ctx.moveTo(toothX, toothY);
                            ctx.lineTo(toothX + Math.cos(angle) * size/20, toothY + Math.sin(angle) * size/20);
                            ctx.lineTo(toothX + Math.cos(angle + 0.2) * size/20, toothY + Math.sin(angle + 0.2) * size/20);
                            ctx.closePath();
                            ctx.fill();
                        }
                        
                        // 绘制血量
                        drawHealthBar(ctx, x, y - size/2, size, healthPercent);
                        
                        // 缓慢的脉动效果
                        const scale = 1 + Math.sin(Date.now()/1000) * 0.02;
                        ctx.save();
                        ctx.translate(x, y);
                        ctx.scale(scale, scale);
                        ctx.restore();
                    }
                },
                bifang: {
                    name: '毕方',
                    color: '#DC2626', // 红色
                    health: 80,
                    speed: 0.8,
                    reward: 100,
                    resistances: ['fire'],
                    draw: function(ctx, x, y, size, healthPercent) {
                        // 毕方身体
                        ctx.fillStyle = this.color;
                        ctx.beginPath();
                        ctx.ellipse(x, y, size/3, size/4, 0, 0, Math.PI * 2);
                        ctx.fill();
                        
                        // 身体纹理
                        ctx.fillStyle = '#B91C1C';
                        for(let i = 0; i < 3; i++) {
                            const yOffset = -size/8 + (i * size/8);
                            ctx.beginPath();
                            ctx.ellipse(x, y + yOffset, size/6 - i*size/30, size/16, 0, 0, Math.PI * 2);
                            ctx.fill();
                        }
                        
                        // 毕方翅膀（动态效果）
                        const time = Date.now() / 500;
                        const wingAngle = Math.sin(time) * 0.3;
                        
                        ctx.fillStyle = '#B91C1C';
                        ctx.save();
                        ctx.translate(x - size/3, y);
                        ctx.rotate(wingAngle);
                        ctx.beginPath();
                        ctx.moveTo(0, 0);
                        ctx.bezierCurveTo(
                            -size/2, -size/3,
                            -size/4, -size/4,
                            0, size/4
                        );
                        ctx.closePath();
                        ctx.fill();
                        ctx.restore();
                        
                        // 毕方头部
                        ctx.fillStyle = '#991B1B';
                        ctx.beginPath();
                        ctx.ellipse(x + size/4, y, size/6, size/6, 0, 0, Math.PI * 2);
                        ctx.fill();
                        
                        // 眼睛
                        ctx.fillStyle = '#FFFFFF';
                        ctx.beginPath();
                        ctx.ellipse(x + size/4 + size/20, y - size/20, size/30, size/30, 0, 0, Math.PI * 2);
                        ctx.fill();
                        
                        ctx.fillStyle = '#000000';
                        ctx.beginPath();
                        ctx.ellipse(x + size/4 + size/18, y - size/20, size/50, size/50, 0, 0, Math.PI * 2);
                        ctx.fill();
                        
                        // 毕方火焰（动态效果）
                        const flameTime = Date.now() / 300;
                        ctx.fillStyle = '#FBBF24';
                        ctx.beginPath();
                        ctx.moveTo(x + size/4, y);
                        ctx.bezierCurveTo(
                            x + size/2 + Math.sin(flameTime) * size/20, y - size/6,
                            x + size/2 + Math.sin(flameTime + 1) * size/20, y + size/6,
                            x + size/4, y
                        );
                        ctx.closePath();
                        ctx.fill();
                        
                        // 火焰外层
                        ctx.fillStyle = '#FB923C';
                        ctx.beginPath();
                        ctx.moveTo(x + size/4 + size/20, y + size/20);
                        ctx.bezierCurveTo(
                            x + size/2 + size/10 + Math.sin(flameTime + 2) * size/15, y - size/6,
                            x + size/2 + size/10 + Math.sin(flameTime + 3) * size/15, y + size/6,
                            x + size/4 + size/20, y + size/20
                        );
                        ctx.closePath();
                        ctx.fill();
                        
                        // 绘制血量
                        drawHealthBar(ctx, x, y - size/2, size, healthPercent);
                    }
                }
            };
            
            // 绘制血条辅助函数
            function drawHealthBar(ctx, x, y, size, percent) {
                // 血条背景
                ctx.fillStyle = '#9CA3AF';
                ctx.fillRect(x - size/2, y, size, size/8);
                
                // 血条填充
                let fillColor = '#10B981'; // 绿色
                if(percent < 30) fillColor = '#EF4444'; // 红色
                else if(percent < 60) fillColor = '#F59E0B'; // 黄色
                
                ctx.fillStyle = fillColor;
                ctx.fillRect(x - size/2, y, size * (percent/100), size/8);
                
                // 血条边框
                ctx.strokeStyle = '#4B5563';
                ctx.lineWidth = 1;
                ctx.strokeRect(x - size/2, y, size, size/8);
            }
            
            // 创建粒子效果
            function createParticles(x, y, count, color, sizeRange = [2, 5]) {
                for(let i = 0; i < count; i++) {
                    const angle = Math.random() * Math.PI * 2;
                    const speed = 1 + Math.random() * 2;
                    const size = sizeRange[0] + Math.random() * (sizeRange[1] - sizeRange[0]);
                    
                    gameState.particles.push({
                        x: x,
                        y: y,
                        size: size,
                        speed: speed,
                        vx: Math.cos(angle) * speed,
                        vy: Math.sin(angle) * speed,
                        color: color,
                        alpha: 1,
                        life: 30 + Math.random() * 20
                    });
                }
            }
            
            // 更新粒子效果
            function updateParticles() {
                for(let i = gameState.particles.length - 1; i >= 0; i--) {
                    const p = gameState.particles[i];
                    
                    // 更新位置
                    p.x += p.vx;
                    p.y += p.vy;
                    
                    // 减速
                    p.vx *= 0.95;
                    p.vy *= 0.95;
                    
                    // 减少生命值
                    p.life--;
                    p.alpha = p.life / 50;
                    
                    // 移除死亡粒子
                    if(p.life <= 0) {
                        gameState.particles.splice(i, 1);
                    }
                }
            }
            
            // 绘制粒子效果
            function drawParticles() {
                gameState.particles.forEach(p => {
                    ctx.save();
                    ctx.globalAlpha = p.alpha;
                    ctx.fillStyle = p.color;
                    ctx.beginPath();
                    ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2);
                    ctx.fill();
                    ctx.restore();
                });
            }
            
            // 更新装饰元素位置
            function updateDecorativeElements() {
                decorativeElements.forEach(el => {
                    el.x += el.speed;
                    if(el.x > 110) {
                        el.x = -10;
                    }
                });
            }
            
            // 绘制装饰元素
            function drawDecorativeElements() {
                decorativeElements.forEach(el => {
                    const pos = getPixelPosition({x: el.x, y: el.y});
                    
                    if(el.type === 'cloud' && cloudImg.complete) {
                        ctx.save();
                        ctx.globalAlpha = 0.6;
                        ctx.drawImage(
                            cloudImg, 
                            pos.x - (cloudImg.width * el.size / 2), 
                            pos.y - (cloudImg.height * el.size / 2),
                            cloudImg.width * el.size,
                            cloudImg.height * el.size
                        );
                        ctx.restore();
                    } else if(el.type === 'bird') {
                        // 绘制简单的鸟形
                        ctx.save();
                        ctx.translate(pos.x, pos.y);
                        ctx.scale(el.size, el.size);
                        
                        ctx.fillStyle = '#2C3E50';
                        ctx.beginPath();
                        ctx.moveTo(0, 0);
                        ctx.lineTo(15, -5);
                        ctx.lineTo(30, 0);
                        ctx.lineTo(15, 5);
                        ctx.closePath();
                        ctx.fill();
                        
                        ctx.restore();
                    }
                });
            }
            
            // 更新游戏状态显示
            function updateGameStatus() {
                moneyEl.textContent = gameState.money;
                livesEl.textContent = gameState.lives;
                waveEl.textContent = `第${gameState.wave}波`;
            }
            
            // 绘制游戏场景
            function drawGame() {
                // 清空画布
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                
                // 绘制背景图（降低透明度）
                if(backgroundImg.complete) {
                    ctx.globalAlpha = 0.5; // 降低背景透明度，防止影响游戏元素观感
                    ctx.drawImage(backgroundImg, 0, 0, canvas.width, canvas.height);
                    ctx.globalAlpha = 1; // 恢复透明度
                }
                
                // 绘制装饰性元素（云、鸟等）
                drawDecorativeElements();
                
                // 绘制路径
                drawPath();
                
                // 绘制起点和终点标记
                drawStartEndPoints();
                
                // 绘制粒子效果
                drawParticles();
                
                // 绘制攻击效果
                drawAttackEffects();
                
                // 绘制敌人
                drawEnemies();
                
                // 绘制防御塔
                drawTowers();
                
                // 绘制塔的攻击范围（当选中时）
                drawTowerRanges();
            }
            
            // 绘制敌人路径
            function drawPath() {
                ctx.beginPath();
                ctx.lineWidth = canvas.height * 0.05; // 路径宽度
                ctx.strokeStyle = 'rgba(139, 69, 19, 0.2)'; // 木色半透明
                
                // 添加路径纹理
                const gradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
                gradient.addColorStop(0, 'rgba(139, 69, 19, 0.1)');
                gradient.addColorStop(0.5, 'rgba(139, 69, 19, 0.3)');
                gradient.addColorStop(1, 'rgba(139, 69, 19, 0.1)');
                ctx.strokeStyle = gradient;
                
                // 将百分比坐标转换为实际像素坐标
                const firstPoint = getPixelPosition(gameState.pathPoints[0]);
                ctx.moveTo(firstPoint.x, firstPoint.y);
                
                // 绘制路径线段
                for(let i = 1; i < gameState.pathPoints.length; i++) {
                    const point = getPixelPosition(gameState.pathPoints[i]);
                    ctx.lineTo(point.x, point.y);
                }
                
                ctx.lineCap = 'round';
                ctx.lineJoin = 'round';
                ctx.stroke();
                
                // 路径边缘
                ctx.lineWidth = canvas.height * 0.005;
                ctx.strokeStyle = 'rgba(139, 69, 19, 0.5)';
                ctx.stroke();
                
                // 路径纹理 - 砖块效果
                ctx.lineWidth = 1;
                ctx.strokeStyle = 'rgba(139, 69, 19, 0.3)';
                
                const segmentLength = canvas.width * 0.05; // 每段长度
                let currentLength = 0;
                
                for(let i = 0; i < gameState.pathPoints.length - 1; i++) {
                    const start = getPixelPosition(gameState.pathPoints[i]);
                    const end = getPixelPosition(gameState.pathPoints[i+1]);
                    const dx = end.x - start.x;
                    const dy = end.y - start.y;
                    const length = Math.sqrt(dx * dx + dy * dy);
                    const dirX = dx / length;
                    const dirY = dy / length;
                    
                    // 绘制垂直于路径的短线段作为纹理
                    for(let j = 0; j < length; j += segmentLength) {
                        const posX = start.x + dirX * j;
                        const posY = start.y + dirY * j;
                        
                        // 垂直方向
                        const perpX = -dirY;
                        const perpY = dirX;
                        
                        // 路径宽度的一半
                        const halfWidth = canvas.height * 0.025;
                        
                        ctx.beginPath();
                        ctx.moveTo(posX + perpX * halfWidth, posY + perpY * halfWidth);
                        ctx.lineTo(posX - perpX * halfWidth, posY - perpY * halfWidth);
                        ctx.stroke();
                    }
                }
            }
            
            // 绘制起点和终点标记
            function drawStartEndPoints() {
                // 起点 - 敌营
                const startPoint = getPixelPosition(gameState.pathPoints[0]);
                
                // 绘制旗帜
                ctx.fillStyle = '#CD5C5C';
                ctx.fillRect(startPoint.x - 5, startPoint.y - 30, 10, 30);
                
                ctx.fillStyle = '#2C3E50';
                ctx.beginPath();
                ctx.moveTo(startPoint.x + 5, startPoint.y - 30);
                ctx.lineTo(startPoint.x + 20, startPoint.y - 40);
                ctx.lineTo(startPoint.x + 5, startPoint.y - 20);
                ctx.closePath();
                ctx.fill();
                
                // 文字
                ctx.fillStyle = '#2C3E50';
                ctx.font = `${canvas.height * 0.025}px 'Ma Shan Zheng', serif`;
                ctx.textAlign = 'center';
                ctx.textBaseline = 'middle';
                ctx.fillText('敌营', startPoint.x - canvas.width * 0.03, startPoint.y);
                
                // 终点 - 关隘
                const endPoint = getPixelPosition(gameState.pathPoints[gameState.pathPoints.length - 1]);
                
                // 绘制城门
                ctx.fillStyle = '#8B4513';
                ctx.fillRect(endPoint.x - 20, endPoint.y - 20, 40, 40);
                
                ctx.fillStyle = '#D2B48C';
                ctx.fillRect(endPoint.x - 10, endPoint.y - 10, 20, 20);
                
                // 文字
                ctx.fillStyle = '#2C3E50';
                ctx.fillText('关隘', endPoint.x + canvas.width * 0.03, endPoint.y);
            }
            
            // 绘制敌人
            function drawEnemies() {
                const enemySize = canvas.height * 0.03; // 敌人大小
                
                gameState.enemies.forEach(enemy => {
                    // 获取当前位置
                    let currentPos;
                    if (enemy.pathIndex < gameState.pathPoints.length - 1) {
                        const currentPoint = gameState.pathPoints[enemy.pathIndex];
                        const nextPoint = gameState.pathPoints[enemy.pathIndex + 1];
                        
                        // 计算当前位置
                        const x = currentPoint.x + (nextPoint.x - currentPoint.x) * enemy.progress;
                        const y = currentPoint.y + (nextPoint.y - currentPoint.y) * enemy.progress;
                        currentPos = getPixelPosition({x, y});
                    } else {
                        currentPos = getPixelPosition(gameState.pathPoints[gameState.pathPoints.length - 1]);
                    }
                    
                    // 计算生命值百分比
                    const healthPercent = (enemy.health / enemy.maxHealth) * 100;
                    
                    // 绘制敌人
                    enemyTypes[enemy.type].draw(ctx, currentPos.x, currentPos.y, enemySize, healthPercent);
                });
            }
            
            // 绘制防御塔
            function drawTowers() {
                const towerSize = canvas.height * 0.04; // 塔的大小
                
                gameState.towers.forEach(tower => {
                    const pos = getPixelPosition({x: tower.x, y: tower.y});
                    towerTypes[tower.type].draw(ctx, pos.x, pos.y, towerSize, tower.level);
                });
            }
            
            // 绘制塔的攻击范围（当选中时）
            function drawTowerRanges() {
                const selectedTowerId = towerInfo.getAttribute('data-tower-id');
                if (!selectedTowerId || towerInfo.style.display === 'none') return;
                
                const tower = gameState.towers.find(t => t.id === selectedTowerId);
                if (!tower) return;
                
                const pos = getPixelPosition({x: tower.x, y: tower.y});
                const rangePixel = (tower.range / 100) * canvas.width; // 将百分比范围转换为像素
                
                // 创建渐变光环
                const gradient = ctx.createRadialGradient(
                    pos.x, pos.y, rangePixel * 0.8,
                    pos.x, pos.y, rangePixel
                );
                gradient.addColorStop(0, 'rgba(218, 165, 32, 0.1)');
                gradient.addColorStop(1, 'rgba(218, 165, 32, 0)');
                
                // 绘制半透明范围圈
                ctx.beginPath();
                ctx.arc(pos.x, pos.y, rangePixel, 0, Math.PI * 2);
                ctx.fillStyle = gradient;
                ctx.fill();
                
                // 范围边界
                ctx.strokeStyle = 'rgba(218, 165, 32, 0.3)';
                ctx.lineWidth = 2;
                ctx.setLineDash([5, 5]);
                ctx.beginPath();
                ctx.arc(pos.x, pos.y, rangePixel, 0, Math.PI * 2);
                ctx.stroke();
                ctx.setLineDash([]); // 重置虚线
            }
            
            // 绘制攻击效果
            function drawAttackEffects() {
                const effectSize = canvas.height * 0.02;
                
                // 清除已结束的效果
                gameState.attackEffects = gameState.attackEffects.filter(effect => {
                    return Date.now() - effect.createdAt < 300; // 效果持续300ms
                });
                
                // 绘制剩余效果
                gameState.attackEffects.forEach(effect => {
                    const pos = getPixelPosition(effect.position);
                    const age = Date.now() - effect.createdAt;
                    const progress = age / 300;
                    
                    // 根据塔类型设置不同的攻击效果颜色
                    let color = 'rgba(218, 165, 32, 1)'; // 默认金色
                    if (effect.towerType === 'fire') color = 'rgba(239, 68, 68, 1)'; // 红色
                    else if (effect.towerType === 'crossbow') color = 'rgba(59, 130, 246, 1)'; // 蓝色
                    else if (effect.towerType === 'light') color = 'rgba(139, 92, 246, 1)'; // 紫色
                    
                    ctx.beginPath();
                    ctx.arc(pos.x, pos.y, effectSize * (1 + progress * 2), 0, Math.PI * 2);
                    ctx.fillStyle = `${color}${Math.floor((1 - progress) * 100) / 100}`;
                    ctx.fill();
                });
            }
            
            // 坐标转换：百分比 -> 像素
            function getPixelPosition(percentPos) {
                return {
                    x: (percentPos.x / 100) * canvas.width,
                    y: (percentPos.y / 100) * canvas.height
                };
            }
            
            // 坐标转换：像素 -> 百分比
            function getPercentPosition(pixelPos) {
                return {
                    x: (pixelPos.x / canvas.width) * 100,
                    y: (pixelPos.y / canvas.height) * 100
                };
            }
            
            // 显示塔预览
            function showTowerPreview(x, y, towerType) {
                if (!towerType) {
                    towerPreview.style.display = 'none';
                    return;
                }
                
                const towerInfo = towerTypes[towerType];
                towerPreview.innerHTML = `<i class="fa ${
                    towerType === 'crossbow' ? 'fa-crosshairs' : 
                    towerType === 'fire' ? 'fa-fire' : 
                    towerType === '八卦' ? 'fa-th' : 'fa-star'
                } text-2xl"></i>`;
                towerPreview.className = `tower-preview ${
                    towerType === 'crossbow' ? 'text-tower-crossbow' : 
                    towerType === 'fire' ? 'text-tower-fire' : 
                    towerType === '八卦' ? 'text-tower-bagua' : 'text-tower-light'
                }`;
                
                towerPreview.style.left = `${x}px`;
                towerPreview.style.top = `${y}px`;
                towerPreview.style.display = 'block';
            }
            
            // 选择防御塔
            towerSelects.forEach(select => {
                select.addEventListener('click', function() {
                    // 移除其他选中状态
                    towerSelects.forEach(s => s.classList.remove('border-primary', 'bg-primary/10'));
                    // 添加当前选中状态
                    this.classList.add('border-primary', 'bg-primary/10');
                    
                    const towerType = this.getAttribute('data-tower');
                    gameState.selectedTower = towerType;
                    
                    showNotification(`已选择${towerTypes[towerType].name}，点击可放置位置进行建造`, 'info');
                });
            });
            
            // 鼠标移动时显示塔预览
            document.addEventListener('mousemove', function(e) {
                if (gameState.selectedTower && gameState.isPlaying) {
                    showTowerPreview(e.clientX + 10, e.clientY - 10, gameState.selectedTower);
                } else {
                    towerPreview.style.display = 'none';
                }
            });
            
            // 放置防御塔
            towerPlaces.forEach(place => {
                place.addEventListener('click', function() {
                    if (!gameState.selectedTower || !gameState.isPlaying) return;
                    
                    const towerType = towerTypes[gameState.selectedTower];
                    const cost = towerType.cost;
                    
                    // 检查是否有足够的钱
                    if (gameState.money < cost) {
                        showNotification('铜钱不足，无法建造此防御塔', 'error');
                        return;
                    }
                    
                    // 检查是否已经放置了塔
                    if (this.classList.contains('tower-place-unavailable')) {
                        return;
                    }
                    
                    // 扣除金钱
                    gameState.money -= cost;
                    updateGameStatus();
                    
                    // 标记为不可用
                    this.classList.remove('tower-place-available');
                    this.classList.add('tower-place-unavailable');
                    
                    // 创建塔
                    const x = parseInt(this.getAttribute('data-x'));
                    const y = parseInt(this.getAttribute('data-y'));
                    const towerId = `tower-${Date.now()}`;
                    
                    const tower = {
                        id: towerId,
                        type: gameState.selectedTower,
                        x: x,
                        y: y,
                        level: 1,
                        attack: towerType.attack,
                        range: towerType.range,
                        speed: towerType.speed,
                        lastAttack: 0
                    };
                    
                    gameState.towers.push(tower);
                    
                    // 创建放置粒子效果
                    const pos = getPixelPosition({x, y});
                    createParticles(
                        pos.x, pos.y, 15, 
                        towerType.color.replace('rgb', 'rgba').replace(')', ', 0.8)'),
                        [3, 6]
                    );
                    
                    showNotification(`成功建造${towerType.name}`, 'success');
                    
                    // 重绘游戏
                    drawGame();
                });
            });
            
            // 显示塔的信息
            function showTowerInfo(tower) {
                const towerType = towerTypes[tower.type];
                
                towerInfoName.textContent = `${towerType.name} Lv.${tower.level}`;
                towerInfoAttack.textContent = tower.attack;
                towerInfoRange.textContent = `${tower.range}%`;
                towerInfoSpeed.textContent = towerType.speed < 800 ? '快' : towerType.speed < 1300 ? '中' : '慢';
                
                // 显示特殊效果
                if (towerType.specialEffect) {
                    towerSpecialEffect.style.display = 'flex';
                    towerEffectText.textContent = towerType.specialEffect;
                } else {
                    towerSpecialEffect.style.display = 'none';
                }
                
                // 存储当前选中的塔ID
                towerInfo.setAttribute('data-tower-id', tower.id);
                
                // 更新升级按钮
                upgradeTower.innerHTML = `<i class="fa fa-level-up mr-1"></i> 升级 (${towerType.upgradeCost * tower.level})`;
                
                // 显示信息面板
                towerInfo.style.display = 'block';
                setTimeout(() => {
                    towerInfo.classList.remove('scale-95', 'opacity-0', 'pointer-events-none');
                }, 10);
                
                // 重绘以显示攻击范围
                drawGame();
            }
            
            // 关闭塔信息
            closeTowerInfo.addEventListener('click', function() {
                towerInfo.classList.add('scale-95', 'opacity-0', 'pointer-events-none');
                setTimeout(() => {
                    towerInfo.style.display = 'none';
                }, 300);
                drawGame(); // 重绘以移除攻击范围显示
            });
            
            // 升级塔
            upgradeTower.addEventListener('click', function() {
                const towerId = towerInfo.getAttribute('data-tower-id');
                const tower = gameState.towers.find(t => t.id === towerId);
                
                if (!tower) return;
                
                const towerType = towerTypes[tower.type];
                const upgradeCost = towerType.upgradeCost * tower.level;
                
                if (gameState.money < upgradeCost) {
                    showNotification('铜钱不足，无法升级此防御塔', 'error');
                    return;
                }
                
                // 扣除金钱
                gameState.money -= upgradeCost;
                updateGameStatus();
                
                // 升级塔
                tower.level += 1;
                tower.attack = Math.round(tower.attack * 1.5);
                tower.range = Math.round(tower.range * 1.2);
                
                // 创建升级粒子效果
                const pos = getPixelPosition({x: tower.x, y: tower.y});
                createParticles(
                    pos.x, pos.y, 20, 
                    '#DAA520',
                    [2, 5]
                );
                
                // 更新显示
                showTowerInfo(tower);
                showNotification(`${towerType.name} 已升级到 Lv.${tower.level}`, 'success');
                
                // 重绘游戏
                drawGame();
            });
            
            // 出售塔
            sellTower.addEventListener('click', function() {
                const towerId = towerInfo.getAttribute('data-tower-id');
                const towerIndex = gameState.towers.findIndex(t => t.id === towerId);
                
                if (towerIndex === -1) return;
                
                const tower = gameState.towers[towerIndex];
                const towerType = towerTypes[tower.type];
                
                // 计算出售价格
                const sellPrice = Math.round((towerType.cost * (tower.level * 0.5)) * 0.7);
                
                // 增加金钱
                gameState.money += sellPrice;
                updateGameStatus();
                
                // 创建出售粒子效果
                const pos = getPixelPosition({x: tower.x, y: tower.y});
                createParticles(
                    pos.x, pos.y, 15, 
                    '#9CA3AF',
                    [2, 4]
                );
                
                // 恢复放置位置可用
                const place = document.querySelector(`.tower-place[data-x="${tower.x}"][data-y="${tower.y}"]`);
                if (place) {
                    place.classList.remove('tower-place-unavailable');
                    place.classList.add('tower-place-available');
                }
                
                // 从数组中移除
                gameState.towers.splice(towerIndex, 1);
                
                showNotification(`已出售${towerType.name}，获得 ${sellPrice} 铜钱`, 'info');
                
                // 关闭信息面板
                towerInfo.classList.add('scale-95', 'opacity-0', 'pointer-events-none');
                setTimeout(() => {
                    towerInfo.style.display = 'none';
                }, 300);
                
                // 重绘游戏
                drawGame();
            });
            
            // 创建敌人
            function createEnemy(type, wave) {
                const enemyType = enemyTypes[type];
                const enemyId = `enemy-${gameState.currentEnemyId++}`;
                
                // 根据波次增强敌人
                const multiplier = 1 + (wave - 1) * 0.2;
                const health = Math.round(enemyType.health * multiplier);
                const reward = Math.round(enemyType.reward * multiplier);
                
                const enemy = {
                    id: enemyId,
                    type: type,
                    health: health,
                    maxHealth: health,
                    speed: enemyType.speed,
                    reward: reward,
                    resistances: enemyType.resistances || [],
                    pathIndex: 0,
                    progress: 0,
                    slowFactor: 1
                };
                
                gameState.enemies.push(enemy);
                
                return enemy;
            }
            
            // 生成一波敌人
            function spawnWave(wave) {
                nextWaveButton.disabled = true;
                const enemyCount = 5 + wave * 2;
                let enemiesSpawned = 0;
                
                showNotification(`第${wave}波敌人正在逼近！`, 'warning');
                
                const spawnInterval = setInterval(() => {
                    if (!gameState.isPlaying) {
                        clearInterval(spawnInterval);
                        return;
                    }
                    
                    if (enemiesSpawned >= enemyCount) {
                        clearInterval(spawnInterval);
                        return;
                    }
                    
                    // 随机选择敌人类型
                    let enemyType;
                    const rand = Math.random();
                    if (rand < 0.6) {
                        enemyType = 'soldier';
                    } else if (rand < 0.85) {
                        enemyType = 'taotie';
                    } else {
                        enemyType = 'bifang';
                    }
                    
                    createEnemy(enemyType, wave);
                    enemiesSpawned++;
                }, 1500);
            }
            
            // 更新敌人位置
            function updateEnemies() {
                gameState.enemies.forEach(enemy => {
                    if (enemy.pathIndex >= gameState.pathPoints.length - 1) {
                        // 到达终点，扣除生命值
                        gameState.lives--;
                        updateGameStatus();
                        
                        // 创建生命值减少效果
                        const endPoint = getPixelPosition(gameState.pathPoints[gameState.pathPoints.length - 1]);
                        createParticles(
                            endPoint.x, endPoint.y, 10, 
                            '#EF4444',
                            [3, 6]
                        );
                        
                        if (gameState.lives <= 0) {
                            showNotification('生命值耗尽！', 'error');
                        } else {
                            showNotification(`敌人突破防线，剩余生命值: ${gameState.lives}`, 'warning');
                        }
                        
                        // 移除敌人
                        removeEnemy(enemy.id);
                        
                        // 检查游戏是否结束
                        if (gameState.lives <= 0) {
                            endGame(false);
                        }
                        return;
                    }
                    
                    // 移动到下一个路径点
                    const currentPoint = gameState.pathPoints[enemy.pathIndex];
                    const nextPoint = gameState.pathPoints[enemy.pathIndex + 1];
                    
                    // 计算距离
                    const dx = nextPoint.x - currentPoint.x;
                    const dy = nextPoint.y - currentPoint.y;
                    const distance = Math.sqrt(dx * dx + dy * dy);
                    
                    // 更新进度（考虑减速效果）
                    enemy.progress += (enemy.speed / distance) * enemy.slowFactor;
                    
                    if (enemy.progress >= 1) {
                        // 到达下一个点
                        enemy.pathIndex++;
                        enemy.progress = 0;
                    }
                    
                    // 重置减速效果（每帧重置，由八卦阵持续施加）
                    if (enemy.slowFactor !== 1) {
                        enemy.slowFactor = Math.min(1, enemy.slowFactor + 0.02);
                    }
                });
            }
            
            // 移除敌人
            function removeEnemy(enemyId) {
                // 从数组中移除
                const enemyIndex = gameState.enemies.findIndex(enemy => enemy.id === enemyId);
                if (enemyIndex !== -1) {
                    const enemy = gameState.enemies[enemyIndex];
                    
                    // 如果是被击杀的，增加统计
                    if (enemy.health <= 0) {
                        gameStats.enemiesKilled++;
                        updateStats();
                        
                        // 创建死亡粒子效果
                        let currentPos;
                        if (enemy.pathIndex < gameState.pathPoints.length - 1) {
                            const currentPoint = gameState.pathPoints[enemy.pathIndex];
                            const nextPoint = gameState.pathPoints[enemy.pathIndex + 1];
                            
                            // 计算当前位置百分比
                            const x = currentPoint.x + (nextPoint.x - currentPoint.x) * enemy.progress;
                            const y = currentPoint.y + (nextPoint.y - currentPoint.y) * enemy.progress;
                            currentPos = getPixelPosition({x, y});
                        } else {
                            currentPos = getPixelPosition(gameState.pathPoints[gameState.pathPoints.length - 1]);
                        }
                        
                        // 根据敌人类型设置粒子颜色
                        let particleColor = '#B45309'; // 默认棕色
                        if (enemy.type === 'taotie') particleColor = '#059669';
                        else if (enemy.type === 'bifang') particleColor = '#DC2626';
                        
                        createParticles(
                            currentPos.x, currentPos.y, 15, 
                            particleColor,
                            [2, 5]
                        );
                    }
                    
                    gameState.enemies.splice(enemyIndex, 1);
                }
                
                // 检查是否所有敌人都被消灭
                if (gameState.enemies.length === 0 && gameState.isPlaying) {
                    nextWaveButton.disabled = false;
                    showNotification(`第${gameState.wave}波敌人已被击退！`, 'success');
                }
            }
            
            // 塔攻击敌人
            function towersAttack() {
                const now = Date.now();
                
                gameState.towers.forEach(tower => {
                    // 检查攻击冷却
                    if (now - tower.lastAttack < tower.speed) {
                        return;
                    }
                    
                    const towerType = towerTypes[tower.type];
                    
                    // 寻找范围内的敌人
                    let target = null;
                    let closestDistance = Infinity;
                    
                    gameState.enemies.forEach(enemy => {
                        // 计算当前敌人位置
                        let enemyPos;
                        if (enemy.pathIndex < gameState.pathPoints.length - 1) {
                            const currentPoint = gameState.pathPoints[enemy.pathIndex];
                            const nextPoint = gameState.pathPoints[enemy.pathIndex + 1];
                            
                            // 计算当前位置百分比
                            const x = currentPoint.x + (nextPoint.x - currentPoint.x) * enemy.progress;
                            const y = currentPoint.y + (nextPoint.y - currentPoint.y) * enemy.progress;
                            enemyPos = {x, y};
                        } else {
                            enemyPos = gameState.pathPoints[gameState.pathPoints.length - 1];
                        }
                        
                        // 计算距离
                        const dx = enemyPos.x - tower.x;
                        const dy = enemyPos.y - tower.y;
                        const distance = Math.sqrt(dx * dx + dy * dy);
                        
                        // 检查是否在范围内
                        if (distance <= tower.range && distance < closestDistance) {
                            closestDistance = distance;
                            target = {enemy, position: enemyPos};
                        }
                    });
                    
                    // 如果有目标，进行攻击
                    if (target) {
                        tower.lastAttack = now;
                        
                        // 记录攻击效果
                        gameState.attackEffects.push({
                            position: target.position,
                            createdAt: now,
                            towerType: tower.type
                        });
                        
                        // 计算伤害（考虑抗性）
                        let damage = tower.attack;
                        if (target.enemy.resistances.includes(tower.type)) {
                            damage = Math.round(damage * 0.3); // 抗性减少70%伤害
                        }
                        
                        // 佛光塔穿透效果
                        if (tower.type === 'light' && tower.level > 1) {
                            // 找到目标后方的其他敌人
                            const additionalTargets = gameState.enemies
                                .filter(e => e.id !== target.enemy.id)
                                .map(enemy => {
                                    let enemyPos;
                                    if (enemy.pathIndex < gameState.pathPoints.length - 1) {
                                        const currentPoint = gameState.pathPoints[enemy.pathIndex];
                                        const nextPoint = gameState.pathPoints[enemy.pathIndex + 1];
                                        const x = currentPoint.x + (nextPoint.x - currentPoint.x) * enemy.progress;
                                        const y = currentPoint.y + (nextPoint.y - currentPoint.y) * enemy.progress;
                                        enemyPos = {x, y};
                                    } else {
                                        enemyPos = gameState.pathPoints[gameState.pathPoints.length - 1];
                                    }
                                    
                                    // 计算与主目标的距离
                                    const dx = enemyPos.x - target.position.x;
                                    const dy = enemyPos.y - target.position.y;
                                    const distance = Math.sqrt(dx * dx + dy * dy);
                                    
                                    return {enemy, distance, position: enemyPos};
                                })
                                .filter(t => t.distance < tower.range * 0.5)
                                .sort((a, b) => a.distance - b.distance)
                                .slice(0, Math.min(tower.level - 1, 2)); // 最多穿透2个目标
                                
                            // 对穿透目标造成伤害
                            additionalTargets.forEach(t => {
                                let pierceDamage = Math.round(damage * 0.6);
                                if (t.enemy.resistances.includes(tower.type)) {
                                    pierceDamage = Math.round(pierceDamage * 0.3);
                                }
                                
                                t.enemy.health -= pierceDamage;
                                
                                // 记录穿透攻击效果
                                gameState.attackEffects.push({
                                    position: t.position,
                                    createdAt: now,
                                    towerType: tower.type
                                });
                                
                                // 检查敌人是否死亡
                                if (t.enemy.health <= 0) {
                                    // 增加金钱奖励
                                    gameState.money += t.enemy.reward;
                                    updateGameStatus();
                                    
                                    // 移除敌人
                                    removeEnemy(t.enemy.id);
                                }
                            });
                        }
                        
                        // 应用伤害
                        target.enemy.health -= damage;
                        
                        // 八卦阵的减速效果
                        if (tower.type === '八卦' && towerType.slow) {
                            target.enemy.slowFactor = Math.max(1 - towerType.slow, target.enemy.slowFactor);
                        }
                        
                        // 烽火台的范围伤害
                        if (tower.type === 'fire') {
                            // 找到范围内的其他敌人
                            const splashTargets = gameState.enemies
                                .filter(e => e.id !== target.enemy.id)
                                .map(enemy => {
                                    let enemyPos;
                                    if (enemy.pathIndex < gameState.pathPoints.length - 1) {
                                        const currentPoint = gameState.pathPoints[enemy.pathIndex];
                                        const nextPoint = gameState.pathPoints[enemy.pathIndex + 1];
                                        const x = currentPoint.x + (nextPoint.x - currentPoint.x) * enemy.progress;
                                        const y = currentPoint.y + (nextPoint.y - currentPoint.y) * enemy.progress;
                                        enemyPos = {x, y};
                                    } else {
                                        enemyPos = gameState.pathPoints[gameState.pathPoints.length - 1];
                                    }
                                    
                                    // 计算与主目标的距离
                                    const dx = enemyPos.x - target.position.x;
                                    const dy = enemyPos.y - target.position.y;
                                    const distance = Math.sqrt(dx * dx + dy * dy);
                                    
                                    return {enemy, distance, position: enemyPos};
                                })
                                .filter(t => t.distance < tower.range * 0.3);
                                
                            // 对范围内敌人造成伤害
                            splashTargets.forEach(t => {
                                let splashDamage = Math.round(damage * 0.5);
                                if (t.enemy.resistances.includes(tower.type)) {
                                    splashDamage = Math.round(splashDamage * 0.3);
                                }
                                
                                t.enemy.health -= splashDamage;
                                
                                // 记录范围攻击效果
                                gameState.attackEffects.push({
                                    position: t.position,
                                    createdAt: now,
                                    towerType: tower.type
                                });
                                
                                // 检查敌人是否死亡
                                if (t.enemy.health <= 0) {
                                    // 增加金钱奖励
                                    gameState.money += t.enemy.reward;
                                    updateGameStatus();
                                    
                                    // 移除敌人
                                    removeEnemy(t.enemy.id);
                                }
                            });
                        }
                        
                        // 检查敌人是否死亡
                        if (target.enemy.health <= 0) {
                            // 增加金钱奖励
                            gameState.money += target.enemy.reward;
                            updateGameStatus();
                            showNotification(`获得 ${target.enemy.reward} 铜钱奖励`, 'info');
                            
                            // 移除敌人
                            removeEnemy(target.enemy.id);
                        }
                    }
                });
            }
            
            // 游戏主循环
            function gameLoop() {
                updateEnemies();
                towersAttack();
                updateParticles();
                updateDecorativeElements();
                drawGame(); // 每帧重绘游戏
            }
            
            // 开始游戏
            function startGame() {
                gameState.isPlaying = true;
                gameOverlay.classList.add('hidden');
                spawnWave(gameState.wave);
                
                // 启动游戏循环
                gameState.gameLoop = setInterval(gameLoop, 30); // 每30ms更新一次（约33FPS）
                
                showNotification('战斗开始！建造防御塔抵御敌人进攻', 'info');
            }
            
            // 下一波
            function nextWave() {
                gameState.wave++;
                gameStats.highestWave = Math.max(gameStats.highestWave, gameState.wave);
                updateGameStatus();
                updateStats();
                spawnWave(gameState.wave);
                
                // 每3波增加一些金钱
                if (gameState.wave % 3 === 0) {
                    const bonus = 200;
                    gameState.money += bonus;
                    updateGameStatus();
                    showNotification(`每3波奖励！获得 ${bonus} 铜钱`, 'success');
                }
            }
            
            // 结束游戏
            function endGame(isVictory) {
                gameState.isPlaying = false;
                clearInterval(gameState.gameLoop);
                
                if (isVictory) {
                    overlayTitle.textContent = '胜利！';
                    overlayMessage.textContent = `你成功抵御了${gameState.wave}波敌人的进攻，守护了长城！`;
                } else {
                    overlayTitle.textContent = '游戏结束';
                    overlayMessage.textContent = `很遗憾，敌人突破了你的防线，长城失守了。你共抵御了${gameState.wave - 1}波敌人。`;
                }
                
                startButton.textContent = '再来一局';
                gameOverlay.classList.remove('hidden');
            }
            
            // 重新开始
            function restartGame() {
                // 清除游戏循环
                if (gameState.gameLoop) {
                    clearInterval(gameState.gameLoop);
                }
                
                // 重置游戏状态
                gameState.money = 500;
                gameState.lives = 10;
                gameState.wave = 1;
                gameState.isPlaying = false;
                gameState.selectedTower = null;
                gameState.towers = [];
                gameState.enemies = [];
                gameState.currentEnemyId = 0;
                gameState.attackEffects = [];
                gameState.particles = [];
                
                // 重置放置点
                towerPlaces.forEach(place => {
                    place.classList.remove('tower-place-unavailable');
                    place.classList.add('tower-place-available');
                });
                
                // 重置塔选择